package com.zcxy.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zcxy.constant.CommonConstant;
import com.zcxy.exception.BusinessException;
import com.zcxy.mybatis.service.BaseServiceImpl;
import com.zcxy.mybatis.service.ValiteCondition;
import com.zcxy.mybatis.util.RelationHelper;
import com.zcxy.sys.constant.Constant;
import com.zcxy.sys.entity.SysDictItem;
import com.zcxy.sys.mapper.SysDictItemMapper;
import com.zcxy.sys.pojo.SysDictItemVo;
import com.zcxy.sys.service.ISysDictItemService;
import com.zcxy.util.BeanCopierUtil;
import com.zcxy.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
 * 子表Service业务层处理
 *
 * @author zcc
 * @email 860474958@qq.com
 * @date 2020-06-04
 */
@Service
@Slf4j
public class SysDictItemServiceImpl extends BaseServiceImpl<SysDictItemMapper, SysDictItem>
        implements ISysDictItemService {
    @Autowired
    private ISysDictItemService iSysDictItemService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateSysDictItem(SysDictItem queryVo) {
        SysDictItem sysDictItemDb = baseMapper.selectById(queryVo.getId());
        validFiledExistUpdate("name", queryVo.getName(), "id", queryVo.getId(), "名称不可重复");
        ValiteCondition valiteCondition = new ValiteCondition("code", queryVo.getCode(), "dictId", queryVo.getDictId());
        validFiledExistUpdate(valiteCondition, "id", queryVo.getId(), "Unicode已存在请勿重复");
        BeanCopierUtil.copyObject(queryVo, sysDictItemDb);
        baseMapper.updateById(sysDictItemDb);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateDisable(List<String> ids) {
        updateSysStatus(Constant.DISABLE, ids);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEnable(List<String> ids) {
        updateSysStatus(Constant.ENABLE, ids);

    }

    public void updateSysStatus(String status, List<String> ids) {
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", ids);
        List<SysDictItem> sysDictItem = baseMapper.selectList(queryWrapper);
        sysDictItem.stream().forEach(i -> {
            i.setStatus(status);
        });
        saveOrUpdateBatch(sysDictItem);
    }

    @Override
    public SysDictItemVo viewSysDictItem(String id) {
        SysDictItem sysDictItem = iSysDictItemService.getBaseMapper().selectById(id);

        SysDictItemVo sysDictItemVo = BeanCopierUtil.copyObject(sysDictItem, SysDictItemVo.class);
        RelationHelper.render(sysDictItemVo);

        return sysDictItemVo;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeAllSysDictItem(List<String> ids) {

        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.in("id", ids);
        baseMapper.delete(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysDictItem> viewSysDictItemsById(String id) {
        QueryWrapper queryWrapper = new QueryWrapper(new SysDictItem());
        queryWrapper.eq("dict_id", id);
        queryWrapper.orderByDesc("create_time");
        List<SysDictItem> SysDictItems = baseMapper.selectList(queryWrapper);
        return SysDictItems;

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void download(SysDictItem queryVo, HttpServletResponse response) throws IOException {
        List<SysDictItem> sysDictItem = baseMapper.selectList(new QueryWrapper<>(queryVo));
        List<Map<String, Object>> list = new ArrayList<>();
        for (SysDictItem sysDictItemExcel : sysDictItem) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("主键", sysDictItemExcel.getId());
            map.put("字典字表的主键", sysDictItemExcel.getDictId());
            map.put("字典值代码", sysDictItemExcel.getCode());
            map.put("字典值名称", sysDictItemExcel.getName());
            map.put("排序", sysDictItemExcel.getSort());
            map.put("注释", sysDictItemExcel.getRemark());
            map.put("状态（0禁用，1启用）", sysDictItemExcel.getStatus());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysDictItem(SysDictItem queryVo) {
        ValiteCondition valiteCondition = new ValiteCondition("code", queryVo.getCode(), "dictId", queryVo.getDictId());
        validFiledExistInsert(valiteCondition, "添加Unicode不可重复");
        validFiledExistInsert("name", queryVo.getName(), "添加名称不可重复");
        queryVo.setDelFlag(CommonConstant.DEL_FLAG_1);
        baseMapper.insert(queryVo);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addSysDictItems(List<String> tArea, String id) {
        List<SysDictItem> sysDictItems = new ArrayList<>();
        tArea.stream().forEach(i -> {
            String[] itemStrs = i.split("\\|");
            SysDictItem sysDictItem = new SysDictItem();
            sysDictItem.setDictId(id);
            sysDictItem.setStatus(CommonConstant.STATUS_NORMAL);
            sysDictItem.setDelFlag(CommonConstant.DEL_FLAG_1);
            for (int k = 0; k < itemStrs.length; k++) {
                if (k == 0) {
                    if (itemStrs[0].equals("")) {
                        throw new BusinessException("名称为空");
                    } else if (itemStrs.length == 1) {
                        throw new BusinessException("Unicode为空");
                    }
                    sysDictItem.setName(itemStrs[0]);
                } else if (k == 1) {
                    if (itemStrs[1].equals("")) {
                        throw new BusinessException("Unicode为空");
                    }
                    sysDictItem.setCode(itemStrs[1]);
                } else if (k == 2) {

                    sysDictItem.setRemark(itemStrs[2]);
                }
            }
            sysDictItems.add(sysDictItem);
        });

        sysDictItems.stream().forEach(i -> {
            validFiledExistInsert("code", i.getCode(), " 添加Unicode不可重复");
            validFiledExistInsert("name", i.getName(), "添加名称不可重复");
        });
        saveBatch(sysDictItems);
    }

}



